export interface IMockFetcher {
    fetcher({
                url,
                method,
                data,
                config,
                headers
            }: { url: string; method: string; data: any; config: any; headers: any }): Promise<any>;
}

export class MockFetcher implements IMockFetcher {

    fetcher({
                url,
                method,
                data,
                config,
                headers
            }: { url: string; method: string; data: any; config: any; headers: any }): Promise<any> {

        let pageId = this.getPageId()

        if (pageId) {
            if (url.startsWith("app/datas/crud")) {
                if (method == 'post') {
                    this.save(pageId, data)
                    return this.success()
                } else {
                    let keywords
                    let match = url.match(new RegExp("(^|&)keywords=([^&]*)(&|$)", "i"))
                    if (match && match.length > 2) {
                        keywords = decodeURI(match[2])
                    }
                    return this.success(this.getList(pageId, keywords))
                }
            } else if (url.startsWith("app/datas/list")) {
                let keywords
                let match = url.match(new RegExp("(^|&)keywords=([^&]*)(&|$)", "i"))
                if (match && match.length > 2) {
                    keywords = decodeURI(match[2])
                }
                return this.success(this.getList(pageId, keywords))
            } else if (url.startsWith("app/datas/add") || url.startsWith("app/datas/update")) {
                this.save(pageId, data)
                return this.success()
            } else if (url.startsWith("app/datas/delete")) {
                this.delete(pageId, data)
                return this.success()
            } else if (url.startsWith("app/datas/batch-edit")) {
                if (data) {
                    this.saveBatch(pageId, data)
                }
                return this.success()
            } else if (url.startsWith("app/datas/batch-delete")) {
                if (data && data.items) {
                    data.items.forEach((item: any) => pageId && this.delete(pageId, item))
                }
                return this.success()
            } else {
                return this.fail(`接口配置错误，接口不存在:${url}`)
            }
        } else {
            return this.fail('接口错误')
        }
    }

    success(data?: any, msg = '操作成功'): Promise<any> {
        return Promise.resolve(
            {
                data: {
                    status: 0,
                    msg: msg,
                    data: data,
                },
                status: 200,
                statusText: '200',
            })
    }

    fail(msg = '操作失败'): Promise<any> {
        return Promise.resolve(
            {
                data: {
                    status: -1,
                    msg: msg,
                },
                status: 200,
                statusText: '200',
            })
    }

    getPageId(): string | undefined {
        let pageId = undefined
        if (location.hash && location.hash.startsWith("#/pages/")) {
            pageId = location.hash.substring("#/pages/".length)
        }
        return pageId
    }

    getList(pageId: string, keywords?: string): any {
        let datas: any = []
        if (pageId && typeof window !== 'undefined' && window.localStorage) {
            const pageData = window.localStorage.getItem(pageId);
            if (pageData) datas = JSON.parse(pageData);
        }
        console.log("keywords", keywords)
        if (datas && datas.length > 0 && keywords) {
            datas = datas.filter((item: any) => {
                let index = Object.getOwnPropertyNames(item).findIndex((key: any) => item[key] && (item[key] + "").indexOf(keywords) > -1)
                return index > -1
            })
        }
        return datas
    }

    save(pageId: string, data: any): boolean {
        let datas = this.getList(pageId)
        console.log("datas1", datas)
        let index = datas.findIndex((item: any) => item.id == data.id)
        if (index > -1) {
            datas[index] = data
        } else {
            datas.push(data)
        }
        console.log("datas1", datas)
        window.localStorage.setItem(pageId, JSON.stringify(datas))
        return true
    }

    saveBatch(pageId: string, data: any): boolean {
        let datas = this.getList(pageId)

        if (datas && data) {
            Object.getOwnPropertyNames(data).forEach((key: any) => {
                if (key != "__super") {
                    datas.forEach((item: any) => {
                        item[key] = data[key]
                    })
                }
            })
        }

        window.localStorage.setItem(pageId, JSON.stringify(datas))
        return true
    }

    delete(pageId: string, data: any): boolean {
        let datas = this.getList(pageId)
        if (datas) {
            datas = datas.filter((item: any) => item.id != data.id)
        }
        window.localStorage.setItem(pageId, JSON.stringify(datas))
        return true
    }
}